<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddUser">新增用户</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="userId" label="用户ID" width="80"/>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="type" label="用户类型" :formatter="formatType"/>
      <el-table-column prop="createdTime" label="创建时间"/>
      <el-table-column prop="updatedTime" label="更新时间"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="currentForm" :rules="rules" ref="userFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogTitle === '新增用户'">
          <el-input v-model="currentForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentForm.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="用户类型" v-if="dialogTitle === '新增用户'">
          <el-select v-model="currentForm.type" placeholder="请选择类型">
            <el-option :value="0" label="管理员"/>
            <el-option :value="1" label="普通用户"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {userDeleteOne, userInsertOne, userSelectPage, userUpdateOne} from "@/api/user.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchForm = reactive({
  phone: '',
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  userId: null,
  username: '',
  password: '',
  email: '',
  phone: '',
  type: 1,
});
const userFormRef = ref(null);

// 验证规则
const rules = {
  username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
  password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {type: 'email', message: '邮箱格式错误', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur'},
  ],
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      phone: searchForm.phone,
    };
    if (!params.phone) {
      delete params.phone;
    }
    const response = await userSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};

// 新增用户
const handleAddUser = () => {
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
  resetForm();
};

// 编辑用户
const handleEditUser = (row) => {
  dialogTitle.value = '编辑用户';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除用户
const handleDeleteUser = (userId) => {
  ElMessageBox.confirm('确认删除该用户?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await userDeleteOne(userId);
      ElMessage.success('删除成功');
      await fetchUsers();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存用户（新增/编辑）
const handleSubmit = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.userId) {
          // 编辑
          await userUpdateOne(currentForm);
        } else {
          // 新增
          await userInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchUsers();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchUsers();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchUsers();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchUsers();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  searchForm.phone = '';
  fetchUsers();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    userId: null,
    username: '',
    password: '',
    email: '',
    phone: '',
    type: 1,
  });
  userFormRef.value?.clearValidate();
};

// 用户类型格式化
const formatType = (row) => {
  if (row.type === 0) {
    return '管理员';
  }
  if (row.type === 1) {
    return '普通用户';
  }
  return '未知用户';
};

// 初始化数据
onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
